package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : SkuServiceImpl  //类名
 * @Description :   //描述
 * @Author : qingfeng  //作者
 * @Date: 2020-09-18 10:57  //时间
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static final String DEDUCT_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";
    private static final String ADD_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.addStock";

    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                //准备参数
                HashMap<String, Object> param = new HashMap<>();
                param.put("id",entry.getKey());
                param.put("num",entry.getValue());
                //编译statement,namespace.statementid
                sqlSession.update(DEDUCT_STOCK_STATEMENT,param);
                //刷新
                sqlSession.flushStatements();
            }
        });
    }

    @Override
    public void addStock(Map<Long, Integer> cartMap) {
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                HashMap<String, Object> param = new HashMap<>();
                param.put("id",entry.getKey());
                param.put("num",entry.getValue());
                sqlSession.update(ADD_STOCK_STATEMENT, param);
                sqlSession.flushStatements();
            }
        });
    }
}
